package com.ant.collect.service.impl;

import com.ant.collect.dto.OrganicDto;
import com.ant.collect.mapper.OrganicMapper;
import com.ant.collect.mapper.OrganicProductMapper;
import com.ant.collect.pojo.Company;
import com.ant.collect.pojo.Organic;
import com.ant.collect.pojo.OrganicProduct;
import com.ant.collect.service.IOrganicService;
import com.ant.collect.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzd
 * @since 2025-10-31
 */
@Service
public class OrganicServiceImpl extends ServiceImpl<OrganicMapper, Organic> implements IOrganicService {

    private static final Logger logger = LoggerFactory.getLogger(Organic.class);

    @Resource
    OrganicProductMapper productMapper;

    @Autowired
    IUserService userService;

    @Override
    public Map<String, Object> queryPageList(OrganicDto dto) {
        try {
            Page<Organic> pageInfo = new Page<Organic>(dto.getPageIndex(), dto.getPageSize());

            QueryWrapper<Organic> wrapper = new QueryWrapper<>();

            if (!ObjectUtils.isEmpty(dto.getAccessoryName())) {
                wrapper.eq("accessory_name", dto.getAccessoryName());
            }
            if (!ObjectUtils.isEmpty(dto.getCompanyId())) {
                wrapper.eq("company_id", dto.getCompanyId());
            }

            Page<Organic> userPage = baseMapper.selectPage(pageInfo, wrapper);
            List<Organic> list = userPage.getRecords();
            list.stream().forEach(item -> {
                List<OrganicProduct> tal =
                        productMapper.selectList(new QueryWrapper<OrganicProduct>()
                                .eq("parent_id", item.getId()));
                item.setProductList(tal);
            });
            Map<String, Object> map = new HashMap<>();
            map.put("list", list);
            map.put("total", userPage.getTotal());
            return map;
        } catch (Exception e) {
            logger.error("查询数据异常", e);
            return null;
        }

    }

    @Override
    public Organic saveOrganic(OrganicDto dto) {
        try {
            // 参数校验
            if (dto == null) {
                throw new IllegalArgumentException("DTO参数不能为空");
            }
            Organic year = new Organic();
            year.setCompanyId(dto.getCompanyId());
            year.setAccessoryName(dto.getAccessoryName());
            year.setAccessoryArea(dto.getAccessoryArea());
            year.setManufacturer(dto.getManufacturer());
            year.setManufacturerTel(dto.getManufacturerTel());
            year.setAccessoryCategory(dto.getAccessoryCategory());
            year.setAccessoryNature(dto.getAccessoryNature());
            year.setAccessoryAgency(dto.getAccessoryAgency());
            year.setAccessoryKind(dto.getAccessoryKind());
            year.setAccessoryType(dto.getAccessoryType());
            year.setAccessoryTypeOne(dto.getAccessoryTypeOne());
            year.setAccessoryTypeTwo(dto.getAccessoryTypeTwo());
            year.setAccessoryCode(dto.getAccessoryCode());
            year.setProcessSteps(dto.getProcessSteps());
            year.setDensity(dto.getDensity());
            year.setVocUrl(dto.getVocUrl());
            year.setReview(1);
            year.setCreationTime(LocalDateTime.now());
            if (dto.getId() == null) {
                // 新增操作
                baseMapper.insert(year);
            } else {
                // 更新操作
                year.setId(dto.getId());
                baseMapper.updateById(year);
            }
            return year;
        } catch (Exception e) {
            logger.error("保存数据异常", e);
            return null;
        }

    }

    @Override
    public List<Organic> listById(Integer id) {
        List<Organic> list = baseMapper.selectList(new QueryWrapper<Organic>().eq("company_id", id));
        list.stream().forEach(item -> {
            item.setProductList(productMapper.selectList(new QueryWrapper<OrganicProduct>().eq("parent_id", item.getId())));
        });
        return list;
    }

    @Override
    public void findApproved(Integer id, Integer status) {
        Organic year = new Organic();
        year.setId(id);
        year.setReview(status);
        baseMapper.updateById(year);
    }

    @Override
    public Organic findOrganicDetails(Integer id) {
        Organic selectOne = baseMapper.selectOne(new QueryWrapper<Organic>().eq("id", id));
        List<OrganicProduct> tal = productMapper.selectList(new QueryWrapper<OrganicProduct>()
                .eq("parent_id", selectOne.getId()));
        selectOne.setProductList(tal);
        return selectOne;
    }

    @Override
    public Map<String, Object> findListCompanyIdPage(OrganicDto dto) {
        Company company = userService.getUserCompanyId();
        Page<Organic> pageInfo = new Page<Organic>(dto.getPageIndex(), dto.getPageSize());
        QueryWrapper<Organic> wrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(dto.getAccessoryName())) {
            wrapper.eq("accessory_name", dto.getAccessoryName());
        }
        if (company != null) {
            wrapper.eq("company_id", company.getId());
        }

        wrapper.eq("review", 2);
        wrapper.orderByDesc("id");
        Page<Organic> userPage = baseMapper.selectPage(pageInfo, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("list", userPage.getRecords());
        map.put("total", userPage.getTotal());
        return map;
    }
}
